// --------------------------------------------------------------------------------------------------------------------
// <copyright file="InverseKinematicsFilterWeightedLeastChange.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Kinematics
{
    using System;

    using Microsoft.Robotics.Tracing;

    using ShoNS.Array;

    /// <summary>
    /// An IK filter that ranks all the joint configurations
    /// based on the weighted changes of each joint with respect to
    /// a given joint configuration.
    /// Joint configurations with less change in all the joints
    /// will be ranked higher than others.
    /// Actual ranking takes place in the base class while
    /// this class provides the score calculator which guides
    /// the ranking process.
    /// </summary>
    public class InverseKinematicsFilterWeightedLeastChange : InverseKinematicsFilter, IDisposable
    {
        /// <summary>
        /// Tracing context for this class
        /// </summary>
        private static TraceContext inverseIKLeastWeightedChangeFilterContext = new TraceContext(0, "IKLeastWeightedChangeFilter", TraceContexts.Manip);

        /// <summary>
        /// The current joint configuration to compared to
        /// </summary>
        private DoubleArray referenceJointConfiguration;

        /// <summary>
        /// The scalar we would like to apply at each dimension
        /// </summary>
        private DoubleArray referenceScalar;

        /// <summary>
        /// Initializes a new instance of the <see cref="InverseKinematicsFilterWeightedLeastChange" /> class.
        /// </summary>
        /// <param name="reference">The reference joint configuration, column vector</param>
        /// <param name="referenceScalar">Reference scalar, column vector</param>
        public InverseKinematicsFilterWeightedLeastChange(DoubleArray reference, DoubleArray referenceScalar = null)
        {
            if (reference.size0 != 1 && reference.size1 != 1)
            {
                throw new System.ArgumentException("The reference joint configuration is not a one-dimensional vector.");
            }

            if (reference.size0 < reference.size1)
            {
                TraceOut.Warning(inverseIKLeastWeightedChangeFilterContext, "The reference joint configuration is not column vector.  A transpose is automatically used");
                this.referenceJointConfiguration = reference.Transpose();
            }
            else
            {
                this.referenceJointConfiguration = reference;
            }

            if (null == referenceScalar)
            {
                this.referenceScalar = new DoubleArray(this.referenceJointConfiguration.Size);
                for (int i = 0; i < this.referenceJointConfiguration.size0; ++i)
                {
                    this.referenceScalar[i] = 1;
                }
            }
            else
            {
                if (referenceScalar.size0 != 1 && referenceScalar.size1 != 1)
                {
                    throw new System.ArgumentException("The reference scalar is not a one-dimensional vector.");
                }

                if (referenceScalar.size0 < referenceScalar.size1)
                {
                    TraceOut.Warning(inverseIKLeastWeightedChangeFilterContext, "The reference scalar is not column vector.  A transpose is automatically used");
                    this.referenceScalar = referenceScalar.Transpose();
                }
                else
                {
                    this.referenceScalar = referenceScalar;
                }
            }
        }
        
        /// <summary>
        /// Calculate how much change has been made to each of the joints, which
        /// is the sum of the absolute changes from the reference joints weighted
        /// by the reference scalar at each dimension.
        /// </summary>
        /// <param name="jointConfiguration">A joint configuration</param>
        /// <returns>A score for this joint configuration</returns>
        public override double ScoreCalculator(DoubleArray jointConfiguration)
        {
            double distance = 0;
            for (int i = 0; i < jointConfiguration.Length; ++i)
            {
                jointConfiguration = jointConfiguration.Transpose();
                double diff = this.referenceScalar[i] * (jointConfiguration[i] - this.referenceJointConfiguration[i]);
                distance += Math.Abs(diff);
            }

            return distance;
        }

        /// <summary>
        /// Disposes of an instance of the <see cref="InverseKinematicsFilterWeightedLeastChange"/> class.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
        }

        /// <summary>
        /// Disposes of an instance of the <see cref="InverseKinematicsFilterWeightedLeastChange"/> class.
        /// </summary>
        /// <param name="disposing">True if disposing, false if finalizing.</param>
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (null != this.referenceScalar)
                {
                    this.referenceScalar.Dispose();
                    this.referenceScalar = null;
                }
            }
        }
    }
}
